package org.huangrui.javase.basic;

import java.util.Scanner;

/**
 * 二分查找
 * @Author hr
 * @Create 2025-11-06 22:55
 **/
public class T08BinarySearch {
    public static void main(String[] args) {
        int[] arr = {8,15,23,35,45,56,75,85};//数组一定是有序的
        Scanner input = new Scanner(System.in);
        System.out.print("请输入你要查找的值：");
        int target = input.nextInt();
        // 一左一右两个指针相向而行
        int index = -1;
        int left = 0;
        int right = arr.length-1;

        while(left<=right){
            int mid = left + (right-left)/2;//计算中间值下标
            if(arr[mid] == target){//找到了
                index = mid;
                break;
            }else if(target < arr[mid]){//说明target在左边
                right= mid-1;//修改右边界，缩小查找范围
            }else if(target > arr[mid]){//说明target在右边
                left = mid+1;//修改左边界，缩小查找范围
            }
        }
        if(index!=-1){
            System.out.println("找到了，下标是"+index);
        }else{
            System.out.println("不存在");
        }
        input.close();
    }
}
